#include "NetworkProcessing.h"
#include "Gateway_Node.h"
#include "SerialScreen.h"

#include "lwip/opt.h"
#include "lwip/sntp.h"

#include <endian.h> // 用于字节序判断

#include "wifi_sta_connect.h"

#if defined(CONFIG_MIDDLEWARE_SUPPORT_NV)
#include "nv.h"
#endif

#include "bsp_led.h"

// 网络通行参数变量
uint8_t g_wifi_mode;         // wifi工作模式  0: Disabled; 1: STA; 2: AP; 3: STA+AP
uint8_t g_wifi_network_mode; // wifi网络传输模式可复用 0x00: Disabled; 0x01: TCP server; 0x02: TCP client; 0x04: UDP; 0x08: MQTT;
uint8_t g_iot_type;          // iot平台类型 0: Disabled; 1: GEC-IoT;
MQTTClient MQTT_client;      // MQTT客户端对象
#define CODE_LOG "[NetworkProcessing]"

// 任务句柄
osal_task *g_TaskHandle_IotMqttConnect = NULL;   // IoT云端MQTT连接
osal_task *g_TaskHandle_IotDataReporting = NULL; // IoT云端数据上报

// 任务函数声明
static void *IotMqttConnect_Task(const char *arg);
static void *IotDataReporting_task(const char *arg);

/**
 * @brief  IoT云端控制指令回复函数。
 * @param  messageId  控制指令的消息ID。
 * @retval ERRCODE_SUCC 成功。
 * @retval Other        失败，参考 @ref errcode_t 。
 **/
errcode_t IoT_MqttControlReply(const char *messageId)
{
    cJSON *root = cJSON_CreateObject(); // 创建JSON对象
    if (root == NULL)
    {
        osal_printk("%s cJSON_CreateObject fail\r\n", CODE_LOG);

        return ERRCODE_FAIL;
    }
    // 添加messageId字段
    if (cJSON_AddStringToObject(root, "messageId", messageId) == NULL)
    {
        osal_printk("%s cJSON_AddStringToObject messageId fail\r\n", CODE_LOG);

        cJSON_Delete(root);
        return ERRCODE_FAIL;
    }
    // 添加output字段
    if (cJSON_AddStringToObject(root, "output", "success") == NULL)
    {
        osal_printk("%s cJSON_AddStringToObject output fail\r\n", CODE_LOG);

        cJSON_Delete(root);
        return ERRCODE_FAIL;
    }
    // 添加success布尔值
    if (cJSON_AddBoolToObject(root, "success", true) == NULL)
    {
        osal_printk("%s cJSON_AddBoolToObject success fail\r\n", CODE_LOG);

        cJSON_Delete(root);
        return ERRCODE_FAIL;
    }

    // 将JSON对象转换为字符串
    char *json_string = cJSON_Print(root);
    // 释放JSON对象，并返回字符串
    cJSON_Delete(root);
    if (json_string == NULL)
    {
        osal_printk("%s cJSON_Print fail\r\n", CODE_LOG);

        return ERRCODE_FAIL;
    }

    // 发布消息
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    pubmsg.payload = json_string;
    pubmsg.payloadlen = (int)strlen(json_string);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    MQTTClient_publishMessage(MQTT_client, IOT_MQTT_TOPIC_CONTROL_REPLY, &pubmsg, &token);
    if (MQTTClient_waitForCompletion(MQTT_client, token, 2000) != MQTTCLIENT_SUCCESS)
    {
        osal_printk("%s Publish message failed\n", CODE_LOG);
    }
    free(json_string); // 释放JSON字符串

    return ERRCODE_SUCC;
}

// MQTT 发送数据回调函数
void IoT_MqttDelivered(void *context, MQTTClient_deliveryToken dt)
{
    osal_printk("%s Message with token value %d delivery confirmed\n", CODE_LOG, dt);
}

// MQTT 收到数据回调函数
/**
 * @brief MQTT 收到数据回调函数
 * @param context MQTT客户端句柄
 * @param topicName MQTT主题
 * @param topicLen MQTT主题长度
 * @param message MQTT消息
 * @return int 1:成功，其他:失败
 * */
int IoT_MqttMsgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    // 调试信息打印
    // osal_printk("%s Message arrived\n", CODE_LOG);
    // osal_printk("%s     topic: %s\n", CODE_LOG, topicName);
    // osal_printk("%s   message: ", CODE_LOG);
    // char *payloadptr = message->payload;
    // for (int i = 0; i < message->payloadlen; i++)
    // {
    //     osal_printk("%c", payloadptr[i]);
    // }
    // osal_printk("\n");

    // 处理IoT云端下发的控制指令
    if (strcmp(topicName, IOT_MQTT_TOPIC_CONTROL_INVOKE) == 0)
    {
        // 解析cJSON消息
        cJSON *msg_cjson = cJSON_Parse(message->payload);
        if (msg_cjson == NULL)
        {
            const char *error_str = cJSON_GetErrorPtr();
            if (error_str != NULL)
            {
                osal_printk("%s cJSON_Parse failed:: %s\n", CODE_LOG, error_str);
            }
            else
            {
                osal_printk("%s cJSON_Parse failed\n", CODE_LOG);
            }

            goto MQTT_Msgarrvd_EXIT;
        }
        cJSON *cjson_msg_data_messageId = cJSON_GetObjectItemCaseSensitive(msg_cjson, "messageId"); // 获取messageId
        if (!cJSON_IsString(cjson_msg_data_messageId) || (cjson_msg_data_messageId->valuestring == NULL))
        {
            osal_printk("%s messageId is not a string\n", CODE_LOG);

            // 销毁JSON对象
            cJSON_Delete(msg_cjson);
            goto MQTT_Msgarrvd_EXIT;
        }
        // osal_printk("%s messageId: %s\n", CODE_LOG, cjson_msg_data_messageId->valuestring);
        cJSON *cjson_msg_data_functionId = cJSON_GetObjectItemCaseSensitive(msg_cjson, "functionId"); // 获取functionId
        if (!cJSON_IsString(cjson_msg_data_functionId) || (cjson_msg_data_functionId->valuestring == NULL))
        {
            osal_printk("%s functionId is not a string\n", CODE_LOG);

            // 销毁JSON对象
            cJSON_Delete(msg_cjson);
            goto MQTT_Msgarrvd_EXIT;
        }
        // osal_printk("%s functionId: %s\n", CODE_LOG, cjson_msg_data_functionId->valuestring);
        const cJSON *resolutions = cJSON_GetObjectItemCaseSensitive(msg_cjson, "inputs");
        uint8_t resolution_count = cJSON_GetArraySize(resolutions);
        // osal_printk("%s resolution_count: %d\n", CODE_LOG, resolution_count);
        if (resolution_count > 1) // 只支持一个控制输入
        {
            osal_printk("%s There can only be one control parameter. resolution_count: %d\n", CODE_LOG, resolution_count);

            // 销毁JSON对象
            cJSON_Delete(msg_cjson);
            goto MQTT_Msgarrvd_EXIT;
        }
        cJSON *cjson_msg_data_inputs_value = cJSON_GetObjectItemCaseSensitive(resolutions->child, "value"); // 获取inputs name
        if (!cJSON_IsString(cjson_msg_data_inputs_value) || (cjson_msg_data_inputs_value->valuestring == NULL))
        {
            osal_printk("%s inputs value is not a string\n", CODE_LOG);

            // 销毁JSON对象
            cJSON_Delete(msg_cjson);
            goto MQTT_Msgarrvd_EXIT;
        }
        // osal_printk("%s inputs value: %s\n", CODE_LOG, cjson_msg_data_inputs_value->valuestring);

        // 处理控制指令  以下代码为样式，需要根据实际需求修改
        // if (strcmp(cjson_msg_data_functionId->valuestring, "relay") == 0) // 控制继电器
        // {
        //     if (strcmp(cjson_msg_data_inputs_value->valuestring, "ON") == 0) // 打开继电器
        //     {
        //         // osal_printk("%s write relay ON event\n", CODE_LOG);
        //         // 写入打开继电器事件
        //         osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_FAN_ON);
        //     }
        //     else if (strcmp(cjson_msg_data_inputs_value->valuestring, "OFF") == 0) // 关闭继电器
        //     {
        //         // osal_printk("%s write relay OFF event\n", CODE_LOG);
        //         // 写入关闭继电器事件
        //         osal_event_write(&g_EventHandle_SystemEvent, SYSTEM_EVENT_FAN_OFF);
        //     }
        // }

        // 回复设备控制
        IoT_MqttControlReply(cjson_msg_data_messageId->valuestring);

        // 销毁JSON对象
        cJSON_Delete(msg_cjson);
    }
    // 处理IoT云端读取设备数据
    else if (strcmp(topicName, IOT_MQTT_TOPIC_DATA_READ) == 0)
    {
        char IotData_Buf[128] = {0};

        // 解析cJSON消息
        cJSON *msg_cjson = cJSON_Parse(message->payload);
        if (msg_cjson == NULL)
        {
            const char *error_str = cJSON_GetErrorPtr();
            if (error_str != NULL)
            {
                osal_printk("%s cJSON_Parse failed:: %s\n", CODE_LOG, error_str);
            }
            else
            {
                osal_printk("%s cJSON_Parse failed\n", CODE_LOG);
            }

            goto MQTT_Msgarrvd_EXIT;
        }
        cJSON *cjson_msg_data_messageId = cJSON_GetObjectItemCaseSensitive(msg_cjson, "messageId"); // 获取messageId
        if (!cJSON_IsString(cjson_msg_data_messageId) || (cjson_msg_data_messageId->valuestring == NULL))
        {
            osal_printk("%s messageId is not a string\n", CODE_LOG);

            // 销毁JSON对象
            cJSON_Delete(msg_cjson);

            goto MQTT_Msgarrvd_EXIT;
        }
        // osal_printk("%s messageId: %s\n", CODE_LOG, cjson_msg_data_messageId->valuestring);
        cJSON *properties = cJSON_GetObjectItem(msg_cjson, "properties"); // 获取 properties 数组
        if (properties == NULL || !cJSON_IsArray(properties))
        {
            osal_printk("%s properties is not an array\n", CODE_LOG);

            // 销毁JSON对象
            cJSON_Delete(msg_cjson);

            goto MQTT_Msgarrvd_EXIT;
        }
        // 根据读取数据类型对设备进行拼接
        cJSON *item = cJSON_GetArrayItem(properties, 0);
        if (cJSON_IsString(item) && strcmp(item->valuestring, "temperature") == 0)
        {
            // osal_printk("%s properties:[ %s ]\n", CODE_LOG, item->valuestring);

            // 拼接JSON字符串
            sprintf(IotData_Buf, "{\"messageId\":\"%s\",\"properties\": {\"temperature\": %2d.%1d}}",
                    cjson_msg_data_messageId->valuestring, g_system_data.Temperature / 10, g_system_data.Temperature % 10);
        }
        else if (cJSON_IsString(item) && strcmp(item->valuestring, "humidity") == 0)
        {
            // osal_printk("%s properties:[ %s ]\n", CODE_LOG, item->valuestring);

            // 拼接JSON字符串
            sprintf(IotData_Buf, "{\"messageId\":\"%s\",\"properties\": {\"humidity\": %2d.%1d}}",
                    cjson_msg_data_messageId->valuestring, g_system_data.Humidity / 10, g_system_data.Humidity % 10);
        }
        else if (cJSON_IsString(item) && strcmp(item->valuestring, "light") == 0)
        {
            // osal_printk("%s properties:[ %s ]\n", CODE_LOG, item->valuestring);

            // 拼接JSON字符串
            sprintf(IotData_Buf, "{\"messageId\":\"%s\",\"properties\": {\"light\": %d}}",
                    cjson_msg_data_messageId->valuestring, g_system_data.Light);
        }

        // 销毁JSON对象
        cJSON_Delete(msg_cjson);

        // MQTT发布主题
        // osal_printk("%s IotData_Buf: %s\n", CODE_LOG, IotData_Buf);
        MQTTClient_message pubmsg = MQTTClient_message_initializer;
        MQTTClient_deliveryToken token;
        pubmsg.payload = IotData_Buf;
        pubmsg.payloadlen = (int)strlen(IotData_Buf);
        pubmsg.qos = QOS;
        pubmsg.retained = 0;
        MQTTClient_publishMessage(MQTT_client, IOT_MQTT_TOPIC_DATA_READ_REPLY, &pubmsg, &token);
        if (MQTTClient_waitForCompletion(MQTT_client, token, 2000) != MQTTCLIENT_SUCCESS)
        {
            osal_printk("%s Publish message failed\n", CODE_LOG);
        }
    }

MQTT_Msgarrvd_EXIT:
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

// MQTT 连接断开回调函数
void IoT_MqttConnlost(void *context, char *cause)
{
    osal_printk("%s Connection lost.", CODE_LOG);
    osal_printk("     cause: %s\n", cause);

    // 关闭LED2，表示MQTT连接已断开
    bsp_led_set_state(LED2, LED_OFF);

    // 上报系统网络状态
    SerialScreen_ReportNetworkState(NETWORK_DISCONNECT);

    // 暂停IoT云端数据上报任务
    osal_kthread_suspend(g_TaskHandle_IotDataReporting);

    // 创建IoT云端连接任务
    osal_msleep(50);
    MQTTClient_destroy(&MQTT_client); // 销毁客户端
    osal_kthread_lock();
    g_TaskHandle_IotMqttConnect = osal_kthread_create((osal_kthread_handler)IotMqttConnect_Task, 0, "IotMqttConnect_Task", 0x1000);
    if (g_TaskHandle_IotMqttConnect != NULL)
    {
        osal_kthread_set_priority(g_TaskHandle_IotMqttConnect, SYSTEM_TASK_PRIORITY_NORMAL);
    }
    else
    {
        osal_printk("ERROR:%s Create IotMqttConnect_Task failed!\n", CODE_LOG);
    }
    osal_kthread_unlock();
}

/**
 * @brief IoT云端MQTT客户端初始化
 * @param client MQTT客户端句柄
 * @param server_addr MQTT服务器地址
 * @param client_id MQTT客户端ID
 * @param sub_topic MQTT订阅主题
 * @param username MQTT用户名
 * @param password MQTT密码
 * @return int 0:成功，其他:失败
 * */
int MQTT_IoTMqttClient_Init(MQTTClient *client, char *server_addr, char *client_id, char *username, char *password)
{
    // MQTT客户端初始化
    MQTTClient_init();

    // MQTT客户端创建
    int rc = MQTTClient_create(client, server_addr, client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        osal_printk("%s Failed to create client, return code %d\n", CODE_LOG, rc);
        return rc;
    }

    // 设置回调函数
    MQTTClient_setCallbacks(*client, NULL, IoT_MqttConnlost, IoT_MqttMsgarrvd, IoT_MqttDelivered);

    // MQTT客户端连接
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    if (username != NULL && password != NULL)
    {
        conn_opts.password = password;
        conn_opts.username = username;
    }
    rc = MQTTClient_connect(*client, &conn_opts);
    if (rc != MQTTCLIENT_SUCCESS)
    {
        osal_printk("%s Failed to connect, return code %d\n", CODE_LOG, rc);
        MQTTClient_destroy(*client); // 销毁客户端

        return rc;
    }

    if (g_iot_type == 1) // 使用了GEC-IoT
    {
        // 打印主题
        osal_printk("%s IOT_MQTT_TOPIC_DATA_REPORT: %s\n", CODE_LOG, IOT_MQTT_TOPIC_DATA_REPORT);
        osal_printk("%s IOT_MQTT_TOPIC_DATA_READ: %s\n", CODE_LOG, IOT_MQTT_TOPIC_DATA_READ);
        osal_printk("%s IOT_MQTT_TOPIC_DATA_READ_REPLY: %s\n", CODE_LOG, IOT_MQTT_TOPIC_DATA_READ_REPLY);
        osal_printk("%s IOT_MQTT_TOPIC_CONTROL_INVOKE: %s\n", CODE_LOG, IOT_MQTT_TOPIC_CONTROL_INVOKE);
        osal_printk("%s IOT_MQTT_TOPIC_CONTROL_REPLY: %s\n", CODE_LOG, IOT_MQTT_TOPIC_CONTROL_REPLY);

        // 订阅主题
        MQTTClient_subscribe(*client, IOT_MQTT_TOPIC_CONTROL_INVOKE, QOS); // 订阅设备控制主题
        MQTTClient_subscribe(*client, IOT_MQTT_TOPIC_DATA_READ, QOS);      // 订阅设备数据读取
    }

    return MQTTCLIENT_SUCCESS;
}

// IoT云端连接任务
static void *IotMqttConnect_Task(const char *arg)
{
    unused(arg);

    // 每3秒连接一次，直到连接成功
    while (1)
    {
        // MQTT客户端连接IoT平台
        char MQTT_Server[128] = {0};
        sprintf(MQTT_Server, "mqtt://%s:%d", g_mqtt_server_ip, g_mqtt_server_port);
        if (MQTT_IoTMqttClient_Init(&MQTT_client, MQTT_Server, g_mqtt_client_id, g_mqtt_username, g_mqtt_password) != MQTTCLIENT_SUCCESS)
        {
            osal_printk("%s MQTT client init fail.\r\n", CODE_LOG);
        }
        else
        {
            // 打开LED2，表示MQTT连接成功
            bsp_led_set_state(LED2, LED_ON);

            // 上报系统网络状态
            SerialScreen_ReportNetworkState(NETWORK_CONNECT);

            // 恢复IoT云端数据上报任务
            osal_kthread_resume(g_TaskHandle_IotDataReporting);

            return NULL; // 连接成功，退出任务
        }

        osal_msleep(3000);
    }

    g_TaskHandle_IotMqttConnect = NULL; //  任务退出，释放句柄
}

// IoT数据上报任务
static void *IotDataReporting_task(const char *arg)
{
    unused(arg);

    // 等待系统数据更新事件
    while (1)
    {
        char IotData_Buf[64] = {0};
        MQTTClient_message pubmsg = MQTTClient_message_initializer;
        MQTTClient_deliveryToken token;

        osal_msleep(30000); // 30s上报一次

        // 温度数据上报
        // 云平台JOSN数据包生成
        sprintf(IotData_Buf, "{\"properties\": {\"temperature\": %2d.%1d}}", g_system_data.Temperature / 10, g_system_data.Temperature % 10);
        // osal_printk("%s IotData_Buf: %s\n", CODE_LOG, IotData_Buf);
        if (g_iot_type == 1) // 使用了GEC-IoT
        {
            // MQTT发布主题
            pubmsg.payload = IotData_Buf;
            pubmsg.payloadlen = (int)strlen(IotData_Buf);
            pubmsg.qos = QOS;
            pubmsg.retained = 0;
            MQTTClient_publishMessage(MQTT_client, IOT_MQTT_TOPIC_DATA_REPORT, &pubmsg, &token);
            if (MQTTClient_waitForCompletion(MQTT_client, token, 2000) != MQTTCLIENT_SUCCESS)
            {
                osal_printk("%s Publish message failed\n", CODE_LOG);
            }
        }

        // 湿度数据上报
        // 云平台JOSN数据包生成
        sprintf(IotData_Buf, "{\"properties\": {\"humidity\": %2d.%1d}}", g_system_data.Humidity / 10, g_system_data.Humidity % 10);
        // osal_printk("%s IotData_Buf: %s\n", CODE_LOG, IotData_Buf);
        if (g_iot_type == 1) // 使用了GEC-IoT
        {
            // MQTT发布主题
            pubmsg.payload = IotData_Buf;
            pubmsg.payloadlen = (int)strlen(IotData_Buf);
            pubmsg.qos = QOS;
            pubmsg.retained = 0;
            MQTTClient_publishMessage(MQTT_client, IOT_MQTT_TOPIC_DATA_REPORT, &pubmsg, &token);
            if (MQTTClient_waitForCompletion(MQTT_client, token, 2000) != MQTTCLIENT_SUCCESS)
            {
                osal_printk("%s Publish message failed\n", CODE_LOG);
            }
        }

        // 光照数据上报
        // 云平台JOSN数据包生成
        sprintf(IotData_Buf, "{\"properties\": {\"light\": %d}}", g_system_data.Light);
        // osal_printk("%s IotData_Buf: %s\n", CODE_LOG, IotData_Buf);
        if (g_iot_type == 1) // 使用了GEC-IoT
        {
            // MQTT发布主题
            pubmsg.payload = IotData_Buf;
            pubmsg.payloadlen = (int)strlen(IotData_Buf);
            pubmsg.qos = QOS;
            pubmsg.retained = 0;
            MQTTClient_publishMessage(MQTT_client, IOT_MQTT_TOPIC_DATA_REPORT, &pubmsg, &token);
            if (MQTTClient_waitForCompletion(MQTT_client, token, 2000) != MQTTCLIENT_SUCCESS)
            {
                osal_printk("%s Publish message failed\n", CODE_LOG);
            }
        }
    }
    return NULL;
}

// Wifi_Sta事件处理函数
void WiFi_STA_EventHandle(uint8_t event, uint8_t *data, uint16_t data_len)
{
    // 状态变化事件
    if (event == WiFi_STA_EVENT_STATE_CHANGE)
    {
        // osal_printk("%s WiFi-sta state change: %d\n", CODE_LOG, *data);

        if (*data == 1) // 连接成功
        {
            osal_printk("%s WiFi-sta connected\n", CODE_LOG);

            // 如果配置了MQTT-IoT通信方式，创建MQTT-IoT通信相关任务
            if (g_wifi_network_mode & 0x08)
            {
                // 创建IoT云端数据上报任务
                osal_msleep(50);
                osal_kthread_lock();
                g_TaskHandle_IotDataReporting = osal_kthread_create((osal_kthread_handler)IotDataReporting_task, 0, "IotDataReporting_Task", 0x1000);
                if (g_TaskHandle_IotDataReporting != NULL)
                {
                    osal_kthread_set_priority(g_TaskHandle_IotDataReporting, SYSTEM_TASK_PRIORITY_NORMAL);
                }
                else
                {
                    osal_printk("ERROR:%s Create IotDataReporting_Task failed!\n", CODE_LOG);
                }
                osal_kthread_unlock();

                // 暂停IoT云端数据上报任务
                osal_kthread_suspend(g_TaskHandle_IotDataReporting);

                // 创建IoT云端连接任务
                osal_msleep(50);
                osal_kthread_lock();
                g_TaskHandle_IotMqttConnect = osal_kthread_create((osal_kthread_handler)IotMqttConnect_Task, 0, "IotMqttConnect_Task", 0x1000);
                if (g_TaskHandle_IotMqttConnect != NULL)
                {
                    osal_kthread_set_priority(g_TaskHandle_IotMqttConnect, SYSTEM_TASK_PRIORITY_NORMAL);
                }
                else
                {
                    osal_printk("ERROR:%s Create IotMqttConnect_Task failed!\n", CODE_LOG);
                }
                osal_kthread_unlock();
            }
        }
        else if (*data == 0) // 断开连接
        {
            osal_printk("%s WiFi-sta disconnected\n", CODE_LOG);

            // 关闭相关任务
            MQTTClient_destroy(&MQTT_client); // 销毁MQTT客户端
            osal_kthread_lock();
            if (g_TaskHandle_IotDataReporting != NULL) // 关闭IoT云端数据上报任务
            {
                osal_kthread_destroy(g_TaskHandle_IotDataReporting, 1);
                g_TaskHandle_IotDataReporting = NULL;
            }
            if (g_TaskHandle_IotMqttConnect != NULL) // 关闭IoT MQTT连接任务
            {
                osal_kthread_destroy(g_TaskHandle_IotMqttConnect, 1);
                g_TaskHandle_IotMqttConnect = NULL;
            }
            osal_kthread_unlock();
        }
    }
}

// 获取编译预处理参数
#if defined(CONFIG_ENABLE_WIFI_IOT_CONFIG)
/**
 * @brief 从预编译配置中，读取WiFi配置信息
 * @param void
 * @retval ERRCODE_SUCC 成功。
 * @retval Other        失败，参考 @ref errcode_t 。
 */
errcode_t SystemGateway_WifiConfigFromKConfig(void)
{
    // 设置为STA模式
    g_wifi_mode = 1;

    // 等待wifi初始化完成
    while (wifi_is_wifi_inited() == 0)
    {
        osal_msleep(100); /* 1: 等待100ms后判断状态 */
    }
    osal_printk("%s wifi init succ.\r\n", CODE_LOG);

    // 设置wifi工作模式
    if (wifi_sta_init(CONFIG_WiFi_SSID, CONFIG_WiFi_PASSWORD, WiFi_STA_EventHandle) != 0)
    {
        osal_printk("%s wifi_sta_init fail.\r\n", CODE_LOG);
        return ERRCODE_FAIL;
    }

    // 设置网络通信标志位
    g_wifi_network_mode |= 0x08; // 设置为MQTT通信方式
    g_iot_type = 1;              // 默认开启GEC-IoT

    return ERRCODE_SUCC;
}

#endif // defined(CONFIG_ENABLE_WIFI_IOT_CONFIG)

/**
 * @brief 系统设备网络配置。 优先级:  编译预处理参数 > NV存储信息
 * @param void
 * @retval ERRCODE_SUCC 成功。
 * @retval Other        失败，参考 @ref errcode_t 。
 */
errcode_t SystemGateway_WifiConfig(void)
{
    errcode_t get_wifi_config_res = ERRCODE_FAIL; // 设备网络配置结果

// 获取编译预处理参数
#if defined(CONFIG_ENABLE_WIFI_IOT_CONFIG)

    // 如果已经获取成功，则直接退出
    if (get_wifi_config_res != ERRCODE_SUCC)
    {
        get_wifi_config_res = SystemGateway_WifiConfigFromKConfig();
        if (get_wifi_config_res == ERRCODE_SUCC)
        {
            osal_printk("%s WiFi config from KConfig\n", CODE_LOG);
        }
    }

#endif // defined(CONFIG_ENABLE_WIFI_IOT_CONFIG)

    return get_wifi_config_res;
}
